package cn.vendsystem.com.service.impl;

import cn.vendcommon.com.entity.InventoryItem;
import cn.vendsystem.com.mapper.InventoryMapper;
import cn.vendsystem.com.service.InventoryService;
import cn.vendsystem.com.utils.AliOssUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品服务实现类
 * （这里先用内存模拟，后续你可以改成 MyBatis + 数据库）
 */
@Service
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Resource
    private InventoryMapper inventoryMapper;

    /**
     * 添加商品
     * @param item 商品
     * @return 添加后的商品
     */
    @Override
    public InventoryItem addInventory(InventoryItem item) {
        inventoryMapper.insert(item);
        return item;
    }

    @Override
    public int deleteInventory(int id) {
        // 删除商品图片
        String picture = inventoryMapper.getPictureById(id);
        if(picture != null && !picture.isEmpty()){
            aliOssUtil.delete(picture);
        }
        return inventoryMapper.deleteById(id);
    }

    /**
     * 更新商品
     * @param item 商品
     * @return 更新后的商品
     */
    @Override
    public InventoryItem updateInventory(InventoryItem item) {
        int result = inventoryMapper.update(item);
        return result > 0 ? item : null;
    }

    /**
     * 根据商品ID查找商品
     * @param id 商品ID
     * @return 商品
     */
    @Override
    public InventoryItem getInventoryById(int id) {
        return inventoryMapper.selectById(id);
    }

    /**
     * 获取所有商品
     * @return 商品列表
     */
    @Override
    public List<InventoryItem> getAllInventory() {
        return inventoryMapper.selectAll();
    }

    /**
     * 根据售卖机ID查找商品
     * @param id 售卖机ID
     * @return 商品列表
     */
    @Override
    public List<InventoryItem> getInventoryByMachineId(int id) {
        return inventoryMapper.selectInventoryByMachineId(id);
    }

    /**
     * 更新商品图片
     * @param id 商品ID
     * @param pictureUrl 图片URL
     */
    @Override
    public void updatePicture(Long id, String pictureUrl) {
        InventoryItem inventory = inventoryMapper.selectById(Math.toIntExact(id));
        if (inventory != null) {
            inventory.setPicture(pictureUrl);
            inventoryMapper.updatePictureById(inventory);
        }
    }

    /**
     * 根据商品ID查找图片URL
     * @param id 商品ID
     * @return 图片URL
     */
    @Override
    public String getPictureById(Integer id) {
        return inventoryMapper.getPictureById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductionInventoryByMachineId(int machineId, Map<String, Integer> intelligentMap) {
        List<InventoryItem> inventoryItems = inventoryMapper.selectInventoryByMachineId(machineId);
        if (inventoryItems == null || inventoryItems.isEmpty()) {
            throw new IllegalArgumentException("未找到machineId=" + machineId + "对应的库存");
        }

        Map<String, InventoryItem> itemMap = inventoryItems.stream()
                .collect(Collectors.toMap(InventoryItem::getName, item -> item));

        for (Map.Entry<String, Integer> entry : intelligentMap.entrySet()) {
            String productName = entry.getKey();
            int deductCount = entry.getValue();

            InventoryItem item = itemMap.get(productName);
            if (item == null) {
                // 如果需要扣减的商品在库存中不存在
                throw new IllegalArgumentException("商品 " + productName + " 不存在于machineId=" + machineId + " 的库存");
            }
            int currentCount = item.getCount();
            if (currentCount < deductCount) {
                // 如果库存不足
                throw new IllegalStateException("商品 " + productName + " 库存不足，当前库存=" + currentCount + "，需要扣减=" + deductCount);
            }

            // 扣减库存
            item.setCount(currentCount - deductCount);
        }
        // 保存库存
        inventoryMapper.updateAll(inventoryItems, machineId);
    }

}
